package cn.tedu.charging.order.config;

import cn.tedu.charging.order.dao.repository.OrderRepository;
import cn.tedu.charging.order.feign.CostClient;
import cn.tedu.charging.order.feign.UserClient;
import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import cn.tedu.charging.order.service.OrderService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {
    //用户名
    private String username="admin";
    //密码
    private String password="public";
    //地址:连接默认端口号是1883
    private String host="tcp://localhost:1883";
    //客户端Id
    private String clientId="order_service_client";
    //mqtt
    private MqttClient mqttClient;

    @Autowired
    private MqttContext mqttContext;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        //通过连接地址和客户端的Id进行连接
        //客户端Id的目的是告诉我们的付曲奇,谁在连接他
        mqttClient = new MqttClient(host,clientId);

        //连接相关的配置
        MqttConnectOptions connOpts = new MqttConnectOptions();
        //用户名
        connOpts.setUserName(username);
        //密码
        connOpts.setPassword(password.toCharArray());
        //自动重连
        connOpts.setAutomaticReconnect(true);
        //版本号设置
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话Session
        connOpts.setCleanSession(true);
        //创建mqtt消费者
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient,mqttContext);
        //设置消费者
        mqttClient.setCallback(mqttConsumer);

        //基于上述的配置进行连接
        mqttClient.connect(connOpts);


        //返回连接客户端
        return mqttClient;
    }
}
